﻿using AutoMapper;
using BCVP.Net8.Repository.Base;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace BCVP.Net8.Service.Base
{
    public class BaseService<TEntity, TVo> : IBaseService<TEntity, TVo> where TEntity : class, new()
    {

        private readonly IMapper _mapper;

        private readonly IBaseRepository<TEntity> _baseRepository;

        public ISqlSugarClient Db => _baseRepository.Db;


        public BaseService(IMapper mapper, IBaseRepository<TEntity> baseRepository)
        {
            _mapper = mapper;
            _baseRepository = baseRepository;
        }

        public async Task<long> Add(TEntity entity)
        {
            return await _baseRepository.Add(entity);
        }

        /// <summary>
        /// 分表查询
        /// </summary>
        /// <param name="whereExpression"></param>
        /// <param name="orderByFields"></param>
        /// <returns></returns>
        public async Task<List<TEntity>> QuerySplit(Expression<Func<TEntity, bool>> whereExpression, string orderByFields = null)
        {
            return await _baseRepository.QuerySplit(whereExpression, orderByFields);
        }

        /// <summary>
        /// 写入实体数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<List<long>> AddSplit(TEntity entity)
        {
            return await _baseRepository.AddSplit(entity);
        }

        /// <summary>
        /// 根据表达式查询
        /// </summary>
        /// <param name="whereExpression"></param>
        /// <returns></returns>
        public async Task<List<TVo>> Query(Expression<Func<TEntity, bool>>? whereExpression = null)
        {
            var entities = await _baseRepository.Query(whereExpression);
            Console.WriteLine($"_baseRepository 实例HashCode ： {_baseRepository.GetHashCode()}");
            var llout = _mapper.Map<List<TVo>>(entities);
            return llout;
        }

    }
}
